package com.bobo.demo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bobo.demo.entity.CaseUndertakeInfo;
import com.bobo.demo.entity.ShakeBead;
import com.bobo.demo.entity.ShakeBeadApply;
import com.bobo.demo.entity.Tuser;
import com.bobo.demo.mapper.DemoMapper;
import com.bobo.demo.service.CaseUndertakeInfoService;
import com.bobo.demo.service.DemoService;
import com.bobo.demo.service.ShakeBeadApplyService;
import com.bobo.demo.service.ShakeBeadService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@Slf4j
@RequiredArgsConstructor
public class DemoServiceImpl extends ServiceImpl<DemoMapper, Tuser>  implements DemoService {

    private  final ShakeBeadApplyService shakeBeadApplyService;

    private  final ShakeBeadService shakeBeadService;

    private  final CaseUndertakeInfoService caseUndertakeInfoService;


//    @Override
//    public void testShakeBead() throws InterruptedException {
//        ShakeBead caseShakeBead = shakeBeadService.getById(1); //拿到工单
//        log.info("摇珠结果->摇珠信息{}", caseShakeBead);
//
//        List<ShakeBeadApply> beadApplyList =  shakeBeadApplyService.list(new QueryWrapper<ShakeBeadApply>().eq("shake_bead_id",caseShakeBead.getId()));
//
//        //赛选结果
//        if (CollUtil.isNotEmpty(beadApplyList)) {
//            //随机筛选出来一个
//            ShakeBeadApply ele = RandomUtil.randomEle(beadApplyList);//赛选结果
//
//            log.info("案件的赛选结果:{}",ele);
//            beadApplyList.remove(ele);
//            updateApplyLawyer(beadApplyList, "失败","生效");//其余的全部失败
//            ele.setState("生效");
//            ele.setResultType("成功");
//            shakeBeadApplyService.updateById(ele);//更新入库
//            caseShakeBead.setState("成功");
//            caseShakeBead.setResultName(ele.getTuserName());
//
//            //更新案件信息
//            List<CaseUndertakeInfo> undertakeInfos = caseUndertakeInfoService.list(new LambdaQueryWrapper<CaseUndertakeInfo>().eq(CaseUndertakeInfo::getCaseCode, "案件[2024]1号"));
//            if (CollUtil.isNotEmpty(undertakeInfos)) {
//                undertakeInfos.forEach(undertakeInfo -> {
//                    undertakeInfo.setTuserId(ele.getTuserId());
//                    undertakeInfo.setTuserName(ele.getTuserName());
//                    undertakeInfo.setShakeBeadId(ele.getShakeBeadId());
//                    caseUndertakeInfoService.updateById(undertakeInfo);
//                });
//            }else{
//                CaseUndertakeInfo info = new CaseUndertakeInfo();
//                info.setTuserId(ele.getTuserId());
//                info.setTuserName(ele.getTuserName());
//                info.setShakeBeadId(ele.getShakeBeadId());
//                info.setCaseCode("案件[2024]:"+LocalDateTime.now());
//                caseUndertakeInfoService.save(info);
//            }
//
//        }else {
//            caseShakeBead.setState("失效");
//        }
//
//        shakeBeadService.updateById(caseShakeBead);
//    }

    @Override
    public void testShakeBead() throws InterruptedException {
        ShakeBead caseShakeBead = shakeBeadService.getById(1); //拿到工单
        log.info("摇珠结果->摇珠信息{}", caseShakeBead);

        List<ShakeBeadApply> beadApplyList = shakeBeadApplyService.list(new QueryWrapper<ShakeBeadApply>().eq("shake_bead_id", caseShakeBead.getId()));

        //赛选结果
        if (CollUtil.isNotEmpty(beadApplyList)) {
            ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建一个具有5个线程的线程池


            executorService.execute(new UpdateAndSaveTask(caseShakeBead,beadApplyList));


            executorService.shutdown(); // 关闭线程池
        } else {
            caseShakeBead.setState("失效");
        }

        shakeBeadService.updateById(caseShakeBead);
    }

    private class UpdateAndSaveTask implements Runnable {
        private ShakeBead caseShakeBead;
        private List<ShakeBeadApply> beadApplyList;
        public UpdateAndSaveTask(ShakeBead caseShakeBead, List<ShakeBeadApply> beadApplyList) {
            this.caseShakeBead = caseShakeBead;
            this.beadApplyList = beadApplyList;
        }

        @Override
        public void run() {
            try {
                updateAndSave(caseShakeBead,beadApplyList);
            } catch (InterruptedException e) {
                log.error("线程被中断", e);
                Thread.currentThread().interrupt();
            }
        }
    }

    private void updateAndSave(ShakeBead caseShakeBead, List<ShakeBeadApply> beadApplyList) throws InterruptedException {
        ShakeBeadApply ele = RandomUtil.randomEle(beadApplyList);
        log.info("案件的赛选结果:{}", ele);
        beadApplyList.remove(ele);
        updateApplyLawyer(beadApplyList, "失败", "生效"); //其余的全部失败
        ele.setState("生效");
        ele.setResultType("成功");
        shakeBeadApplyService.updateById(ele);//更新入库
        caseShakeBead.setState("成功");
        caseShakeBead.setResultName(ele.getTuserName());

        Thread.sleep(3000);
        List<CaseUndertakeInfo> undertakeInfos = caseUndertakeInfoService.list(new LambdaQueryWrapper<CaseUndertakeInfo>().eq(CaseUndertakeInfo::getCaseCode, "案件[2024]1号"));
        if (CollUtil.isNotEmpty(undertakeInfos)) {
            undertakeInfos.forEach(undertakeInfo -> {
                undertakeInfo.setTuserId(ele.getTuserId());
                undertakeInfo.setTuserName(ele.getTuserName());
                undertakeInfo.setShakeBeadId(ele.getShakeBeadId());
                caseUndertakeInfoService.updateById(undertakeInfo);
            });
        } else {
            CaseUndertakeInfo info = new CaseUndertakeInfo();
            info.setTuserId(ele.getTuserId());
            info.setTuserName(ele.getTuserName());
            info.setShakeBeadId(ele.getShakeBeadId());
            info.setCaseCode("案件[2024]:" + LocalDateTime.now());
            caseUndertakeInfoService.save(info);
        }
        shakeBeadService.updateById(caseShakeBead);
    }


    public Boolean updateApplyLawyer(List<ShakeBeadApply> list, String state, String resultType) {
        if (CollUtil.isEmpty(list)) {
            return Boolean.FALSE;
        }
        list.forEach(item -> {
            item.setResultType(resultType);
            item.setResultType(state);
        });
        return shakeBeadApplyService.updateBatchById(list);
    }

}
